import Qfpage from "../../components/Qfpage/Qfpage";
import React from 'react';
import 'antd/dist/antd.css';
import { Space, Table, Tag, Pagination, Button, Col, DatePicker, Drawer, Form, Input, Row, Select, InputNumber, Popconfirm, message, Modal, Radio, Cascader } from 'antd';
import { useMemo, useEffect, useState, useRef, useLayoutEffect } from "react";
import { getAllRoom, delRoom, addRoom, editRoom } from '../../api/room'
import { getAllBuild } from "../../api/bulid";
import { getAllType } from "../../api/roomType";
import './style.scss'


const RoomList = () => {
    // 获取全部的楼栋信息
    const [build, setBuild] = useState([])
    const getBuild = async () => {
        let res = await getAllBuild({});
        console.log('res', res)
        const temarr = res.data.map(item => ({
            label: item.name,
            value: item._id,
            children: item.floorInfo.map(it => ({ label: it, value: it }))
        }))
        setBuild(temarr)
        console.log('bulid', build)
    }
    useEffect(() => {
        getBuild();  // 获取楼栋信息
    }, [])


    // 获取全部的房型

    const [type, setType] = useState([]);
    const getTypes = async () => {
        const res = await getAllType({ limit: 2000 });
        setType(res.data.map(item => ({ label: item.name, value: item._id })))
    }
    console.log(type)
    useEffect(() => {
        getTypes();  // 获取全部的房型信息
    }, [])


    const [data, setData] = useState([]);
    const [limit, setLimit] = useState(30);  // 单页数量
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0); // 总数
    // 获取表格数据的主函数
    const getData = async () => {
        const postData = { limit, page };
        if (name) postData.name = name;
        if (price) postData.price = price;

        let res = await getAllRoom(postData)
        const { success, data, count } = res;
        if (success) {
            setData(data);
            setTotal(count)
        };
    }

    // 条件过滤
    const [name, setName] = useState('');
    const [price, setPrice] = useState('')


    useLayoutEffect(() => {
        getData(); // 获取表格数据

    }, [limit, page])

    const columns = useMemo(() => [
        {
            title: '房型名称',
            dataIndex: 'roomName',
            Key: 'roomName',
        },
        {
            title: '楼层',
            dataIndex: 'floor',
            Key: 'floor',
        },
        {
            title: '方向朝向',
            dataIndex: 'direction',
            Key: 'direction',
            onCell: (rowIndex) => {
                console.log('rowIndex', rowIndex);
            }
        },
        {
            title: '是否有窗',
            dataIndex: 'hasWindow',
            Key: 'hasWindow',
            onCell :(rowIndex) =>{
                console.log('rowIndex',rowIndex);}
        },
        {
            title: '靠近马路',
            dataIndex: 'isClose2Road',
            Key: 'isClose2Road',
        },
        {
            title: '允许吸烟',
            dataIndex: 'isSmoke',
            Key: 'isSmoke',
        },
        {
            title: '高温房',
            dataIndex: 'isHigh',
            Key: 'isHigh',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, row) =>
                <>
                    <Button onClick={() => handlerDel(row._id)} ghost danger>
                        删除
                    </Button>
                    <Button style={{ marginLeft: '5px' }} onClick={() => openEdit(row)} type="primary" ghost>
                        修改
                    </Button>
                </>

        }

    ], [])




    const rules = {// 表单的校验规则
        roomName: [{ required: true, message: '不可能不填吧', type: 'error' }],
        bandf: [{ required: true, message: '不可能不填吧', type: 'error' }],
        type: [{ required: true, message: '不可能不填吧', type: 'error' }],
        direction: [{ required: true, message: '不可能不填吧', type: 'error' }],
        isClose2Road: [{ required: true, message: '不可能不填吧', type: 'error' }],
        isSmoke: [{ required: true, message: '不可能不填吧', type: 'error' }],
        isNoise: [{ required: true, message: '不可能不填吧', type: 'error' }],
        isHigh: [{ required: true, message: '不可能不填吧', type: 'error' }],


    }

    // 添加房型的操作(抽屉)
    const [visible, setVisible] = useState(false);

    const showDrawer = () => {
        setVisible(true);//显示抽屉
    };

    const onClose = () => {
        setVisible(false);//隐藏抽屉
    };
    // ******************添加房间操作***************************
    const refFrom = useRef(null)
    const handleAdd = async () => {
        const values = refFrom.current.getFieldsValue(true); // 得到所有的表单的值
        const { bandf, ...postData } = values;
        const [buildId, floor] = bandf;
        let res = await addRoom({
            ...postData,
            floor,
            buildId
        });
        const { success } = res
        if (!success) return message.warning('添加失败');
        message.success('添加成功')
        getData();// 刷新表格
        onClose();//关闭抽屉
        refFrom.current.resetFields()//表单重置
    }


    // ************删除房间***************************
    const confirmDel = async (id) => {
        let res = await delRoom({ roomid: id });
        const { success } = res;
        if (!success) return message.warning('删除失败')
        message.success('删除成功');
        getData();
    }

    const { confirm } = Modal;
    const destroyAll = () => {
        Modal.destroyAll();
    };
    const handlerDel = (id) => {
        confirm({
            content: <Button onClick={destroyAll}>确定要删除吗？</Button>,
            onOk() {
                console.log('OK');
                confirmDel(id)
            },
            onCancel() {
                console.log('Cancel');
            },
        });


    };

    // **********修改房间**********************
    const [showEdit, setShowEdit] = useState(false);
    const editRef = useRef(null);
    const [curRow, setCurRow] = useState(null)
    const openEdit = (row) => {
        setCurRow(row)
        // 设置 修改表单的内容
        editRef.current.setFieldsValue({
            ...row,
            bandf: [row.buildId, row.floor]
        })
        setShowEdit(true); //  让修改抽屉弹出
    }
    const handleEdit = async () => {
        const values = editRef.current.getFieldsValue(true); // 得到所有的表单的值
        const { bandf, ...postData } = values;
        const [buildId, floor] = bandf;
        // 发送请求执行修改
        let res = await editRoom({
            ...postData,
            roomid: curRow._id,
            buildId,
            floor
        });
        const { success } = res;
        if (!success) return message.warning('修改失败');
        message.success('修改成功');
        getData(); // 刷新表格
        setShowEdit(false) // 抽屉隐藏
    }

    return (
        <Qfpage title="设置">
            <div>房间管理</div>
            <div>
                <Button type="primary" style={{ marginTop: '10px' }} onClick={showDrawer}>添加房间</Button>
                <div style={{ marginLeft: '60%', display: "flex" }}>
                </div>
            </div>
            <Table
                columns={columns}
                dataSource={data}
                Pagination={{
                    defaultPageSize: limit,
                    total: { total },
                    onChange({ pageSize, current }) {
                        setPage(current);
                        setLimit(pageSize)

                    }
                }}
            />

            {/* 增加房型的抽屉 */}
            <Drawer
                width={500}
                onClose={onClose}
                visible={visible}
                bodyStyle={{
                    paddingBottom: 80,
                }}
            >
                <Form layout="vertical"
                    ref={refFrom}
                    rules={rules}>
                    <Popconfirm
                        icon={null}
                        onConfirm={handleAdd}
                        onCancel={onClose}
                        okText="添加"
                        cancelText="取消"
                    >
                        <Button type="primary">是否确定添加</Button>
                    </Popconfirm>
                    <Form.Item
                        name="roomName"
                        label="房间名"
                        rules={[
                            {
                                required: true,
                                message: '请填写房间名',
                            },
                        ]}
                    >
                        <Input placeholder="请填写房间名" />
                    </Form.Item>
                    <Form.Item
                        name='bandf'
                        label='所在楼栋楼层'
                        rules={[
                            {
                                required: true,
                                message: '楼栋楼层为必填',
                            }
                        ]}
                    >
                        <Cascader
                            options={build}
                            placeholder="请选择楼栋楼层"
                        />
                    </Form.Item>

                    <Form.Item
                        label="选择房型"
                        name="type"
                        rules={[
                            {
                                required: true,
                                message: '房型为必填',
                            }
                        ]}
                    >
                        <Select
                            placeholder="请选择房型"
                            options={type}
                        >
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="phone4in"
                        label="内线电话"
                        rules={[
                            {
                                required: true,
                                message: '请填写内线电话',
                            },
                        ]}
                    >
                        <Input placeholder="请填写内线电话" />
                    </Form.Item>
                    <Form.Item
                        name="phone4out"
                        label="外线电话"
                        rules={[
                            {
                                required: true,
                                message: '请填写外线电话',
                            },
                        ]}
                    >
                        <Input placeholder="请填写外线电话" />
                    </Form.Item>
                    <Form.Item
                        name='direction'
                        label="方向朝向"
                    >
                        <Radio.Group defaultValue="东">
                            <Radio.Button value="东">东</Radio.Button>
                            <Radio.Button value="西">西</Radio.Button>
                            <Radio.Button value="南">南</Radio.Button>
                            <Radio.Button value="北">北</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否有窗户"
                        name="hasWindow"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否靠近马路"
                        name="isClose2Road"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否允许吸烟"
                        name="isSmoke"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是噪音房"
                        name="isNoise"
                    >
                        <Radio.Group defaultValue={false} >
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是高温房"
                        ame="isHigh"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                </Form>

            </Drawer>

            {/* 修改房型的抽屉 */}
            <Drawer
                forceRender={true}
                width={500}
                closable={false}
                onClose={onClose}
                visible={showEdit}
                bodyStyle={{
                    paddingBottom: 80,
                }}
            >
                <Form layout="vertical"
                    ref={editRef}
                    rules={rules}>
                    <Popconfirm
                        icon={null}
                        onConfirm={handleEdit}
                        onCancel={onClose}
                        okText="修改"
                        cancelText="取消"
                    >
                        <Button type="primary">是否确定修改</Button>
                    </Popconfirm>
                    <Form.Item
                        name="roomName"
                        label="房间名"
                        rules={[
                            {
                                required: true,
                                message: '请填写房间名',
                            },
                        ]}
                    >
                        <Input placeholder="请填写房间名" />
                    </Form.Item>
                    <Form.Item
                        name='bandf'
                        label='所在楼栋楼层'
                        rules={[
                            {
                                required: true,
                                message: '楼栋楼层为必填',
                            }
                        ]}
                    >
                        <Cascader
                            options={build}
                            placeholder="请选择楼栋楼层"
                        />
                    </Form.Item>

                    <Form.Item
                        label="选择房型"
                        name="type"
                        rules={[
                            {
                                required: true,
                                message: '房型为必填',
                            }
                        ]}
                    >
                        <Select
                            placeholder="请选择房型"
                            options={type}
                        >
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="phone4in"
                        label="内线电话"
                        rules={[
                            {
                                required: true,
                                message: '请填写内线电话',
                            },
                        ]}
                    >
                        <Input placeholder="请填写内线电话" />
                    </Form.Item>
                    <Form.Item
                        name="phone4out"
                        label="外线电话"
                        rules={[
                            {
                                required: true,
                                message: '请填写外线电话',
                            },
                        ]}
                    >
                        <Input placeholder="请填写外线电话" />
                    </Form.Item>
                    <Form.Item
                        name='direction'
                        label="方向朝向"
                    >
                        <Radio.Group defaultValue="1">
                            <Radio.Button value="1">东</Radio.Button>
                            <Radio.Button value="2">西</Radio.Button>
                            <Radio.Button value="3">南</Radio.Button>
                            <Radio.Button value="4">北</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否有窗户"
                        name="hasWindow"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否靠近马路"
                        name="isClose2Road"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否允许吸烟"
                        name="isSmoke"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是噪音房"
                        name="isNoise"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是高温房"
                        ame="isHigh"
                    >
                        <Radio.Group defaultValue={false}>
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                </Form>

            </Drawer>
        </Qfpage>
    )
}

export default RoomList;